package com.epfly.promo.activity.impl.discount;

import com.epfly.iface.promo.activity.enums.DiscountTypeEnum;
import com.epfly.promo.activity.entity.ActivityRuleEntity;
import com.epfly.promo.activity.impl.discount.content.OrderRebate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Comparator;


/**
 * 2.折扣;
 * {@link DiscountTypeEnum#FOOD_REBATE}
 */
@Service
public class OrderRebateDiscountFunction extends AbstractDiscountFunction {


    @Override
    public BigDecimal doApply(ActivityWrapper activityWrapper, ActivityRuleEntity ruleEntity) {

        BigDecimal payAmount = activityWrapper.getPayAmount();
        String ruleContent = ruleEntity.getRuleContent();
        OrderRebate orderRebate = gson.fromJson(ruleContent, OrderRebate.class);

        BigDecimal totalRebate = orderRebate.getValues().stream().map(e -> {
            if (payAmount.compareTo(e.getUpperBound()) >= 0) {
                BigDecimal rebatePrice = e.getDiscountPercent().multiply(payAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                return rebatePrice;
            }
            return BigDecimal.ZERO;
        }).max(Comparator.naturalOrder()).get();
        return totalRebate;
    }

    @Override
    public Byte getDiscountType() {
        return DiscountTypeEnum.FOOD_REBATE.getKey();
    }
}
